
export class MapDraw {
    constructor(map) {
        if (!map) {
            throw new Error('百度地图实例不能为空');
        }
        this.map = map;
        this.options = {};
        this.mode = 'none';
        this.overlays = {
            markers: [],
            polylines: [],      // 存储已完成的线段
            tempPolylines: []   // 存储临时/正在绘制的线段
        };
        this.currentLine = [];
        this.tempLine = null;
        this.lastPoint = null;
        this.currentPolyline = null;
        this.undoStack = [];
        this.snapDistance = 10; // 吸附距离（像素）

        // 添加标志位和定时器
        this.isDoubleClick = false;
        this.dblClickTimer = null;

        // 绑定事件处理函数的上下文
        this._handleMapClick = this._handleMapClick.bind(this);
        this._handleMapMove = this._handleMapMove.bind(this);
        this._handleMapDblClick = this._handleMapDblClick.bind(this);
        this._handleKeyDown = this._handleKeyDown.bind(this);
    }

    deleteAllPoints() {
        this.overlays.markers.forEach(marker => {
            this.map.removeOverlay(marker);
        });
        this.overlays.markers = [];
    }

    deleteAllLines() {
        // 清除已完成的线段
        this.overlays.polylines.forEach(polyline => {
            this.map.removeOverlay(polyline);
        });
        this.overlays.polylines = [];

        // 清除临时线段
        this.overlays.tempPolylines.forEach(polyline => {
            this.map.removeOverlay(polyline);
        });
        this.overlays.tempPolylines = [];
    }

    addPoint(lng, lat, options = {}) {
        const point = new BMapGL.Point(lng, lat);
        let marker;

        if (options.iconUrl) {
            const icon = new BMapGL.Icon(options.iconUrl, new BMapGL.Size(20, 20));
            marker = new BMapGL.Marker(point, { icon });
        } else {
            marker = new BMapGL.Marker(point);
        }

        if (options.title) {
            const label = new BMapGL.Label(options.title, { offset: new BMapGL.Size(20, -10) });
            label.setStyle({
                color: '#1a1a1a',
                fontSize: '0.8em',
                backgroundColor: 'rgba(255, 255, 255, 0.95)',
                border: '1px solid #e0e0e0',
                borderRadius: '4px',
                padding: '5px 10px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
                fontWeight: '500',
                letterSpacing: '0.3px'
            });
            marker.setLabel(label);
        }

        const contextMenu = new BMapGL.ContextMenu();
        const deleteMenuItem = new BMapGL.MenuItem('删除标记', () => {
            if (options.onRemoveMarker) {
                options.onRemoveMarker(options.info);
            }
        });

        contextMenu.addItem(deleteMenuItem);
        marker.addContextMenu(contextMenu);
        this.map.addOverlay(marker);
        this.overlays.markers.push(marker);
        return marker;
    }

    addLine(points, options = {}) {
        if (!Array.isArray(points) || points.length < 2) {
            throw new Error('添加线条需要至少两个点');
        }

        const bmapPoints = points.map(p => new BMapGL.Point(p.lng, p.lat));
        const polyline = new BMapGL.Polyline(bmapPoints, {
            strokeColor: options.strokeColor || '#FF0000',
            strokeWeight: options.strokeWeight || 2,
            strokeOpacity: options.strokeOpacity || 1.0,
            enableEditing: false,
            enableMassClear: true,
        });

        // 标记为已完成的线段
        polyline.isCompleted = true;

        const contextMenu = new BMapGL.ContextMenu();
        const deleteMenuItem = new BMapGL.MenuItem('删除线段', () => {
            if (options.onRemoveLine) {
                options.onRemoveLine(options.id);
            }
        });

        contextMenu.addItem(deleteMenuItem);
        polyline.addContextMenu(contextMenu);

        this.map.addOverlay(polyline);
        this.overlays.polylines.push(polyline);
        this.undoStack.push({ type: 'line', overlay: polyline });
        return polyline;
    }

    startDrawing(type, options) {
        this.mode = type;
        this.options = options;
        this.map.setDefaultCursor('crosshair');
        this.map.addEventListener('click', this._handleMapClick);
        this.map.addEventListener('mousemove', this._handleMapMove);
        this.map.addEventListener('dblclick', this._handleMapDblClick);
        document.addEventListener('keydown', this._handleKeyDown);
    }

    stopDrawing(result) {
        this.mode = 'none';

        // 移除所有事件监听
        this.map.removeEventListener('click', this._handleMapClick);
        this.map.removeEventListener('mousemove', this._handleMapMove);
        this.map.removeEventListener('dblclick', this._handleMapDblClick);
        document.removeEventListener('keydown', this._handleKeyDown);

        // 清理临时绘制的内容
        if (this.tempLine) {
            this.map.removeOverlay(this.tempLine);
            this.tempLine = null;
        }

        // 清理未完成的当前线段
        if (this.currentPolyline && !this.currentPolyline.isCompleted) {
            this.map.removeOverlay(this.currentPolyline);
            const index = this.overlays.tempPolylines.indexOf(this.currentPolyline);
            if (index > -1) {
                this.overlays.tempPolylines.splice(index, 1);
            }
            this.currentPolyline = null;
        }

        // 如果有结果则调用 onDrawEnd
        if (result && this.options.onDrawEnd) {
            this.options.onDrawEnd(result);
        }

        // 重置所有状态
        this.options = {};
        this.map.setDefaultCursor('default');
        this.currentLine = [];
        this.lastPoint = null;
    }

    _handleMapClick(e) {
        if (this.isDoubleClick) {
            this.isDoubleClick = false;
            return;
        }

        if (this.mode === 'none') {
            return;
        }

        if (this.mode === 'point') {
            this.addPoint(e.latlng.lng, e.latlng.lat, this.options);
            this.stopDrawing({ point: { lng: e.latlng.lng, lat: e.latlng.lat } });
        }
        if (this.mode === 'line') {
            const snappedPoint = this._snapToNearestPoint(e.latlng);
            this.currentLine.push(snappedPoint);
            this.lastPoint = snappedPoint;

            if (this.currentPolyline) {
                const path = this.currentPolyline.getPath();
                path.push(new BMapGL.Point(snappedPoint.lng, snappedPoint.lat));
                this.currentPolyline.setPath(path);
            } else {
                this.currentPolyline = new BMapGL.Polyline(
                    this.currentLine.map(p => new BMapGL.Point(p.lng, p.lat)),
                    {
                        strokeColor: this.options.strokeColor || '#FF0000',
                        strokeWeight: this.options.strokeWeight || 2,
                        strokeOpacity: this.options.strokeOpacity || 1.0,
                        enableEditing: false,
                        enableMassClear: true,
                    }
                );
                this.currentPolyline.isCompleted = false; // 标记为未完成的线段
                this.map.addOverlay(this.currentPolyline);
                this.overlays.tempPolylines.push(this.currentPolyline);
            }

            this.undoStack.push({
                type: 'linePoint',
                point: snappedPoint,
                polyline: this.currentPolyline
            });
        }
    }

    _handleMapMove(e) {
        if (this.mode === 'line' && this.lastPoint) {
            const snappedPoint = this._snapToNearestPoint(e.latlng);

            if (this.tempLine) {
                this.map.removeOverlay(this.tempLine);
            }

            this.tempLine = new BMapGL.Polyline(
                [
                    new BMapGL.Point(this.lastPoint.lng, this.lastPoint.lat),
                    new BMapGL.Point(snappedPoint.lng, snappedPoint.lat)
                ],
                {
                    strokeColor: '#00FF00',
                    strokeWeight: 2,
                    strokeOpacity: 0.7,
                    enableEditing: false,
                    enableMassClear: true,
                }
            );
            this.map.addOverlay(this.tempLine);
        }
    }

    _handleMapDblClick(e) {
        if (this.mode === 'line') {
            e.domEvent.preventDefault();

            this.isDoubleClick = true;
            clearTimeout(this.dblClickTimer);
            this.dblClickTimer = setTimeout(() => {
                this.isDoubleClick = false;
            }, 300);

            if (this.tempLine) {
                const snappedPoint = this._snapToNearestPoint(e.latlng);
                if (this.currentLine.length === 0 ||
                    this._calculateDistance(snappedPoint, this.currentLine[this.currentLine.length - 1]) > 5) {
                    this.currentLine.push(snappedPoint);
                }
                this.map.removeOverlay(this.tempLine);
                this.tempLine = null;
            }

            if (this.currentLine.length >= 2) {
                const lineSegments = [];
                for (let i = 0; i < this.currentLine.length - 1; i++) {
                    const start = this.currentLine[i];
                    const stop = this.currentLine[i + 1];

                    if (start.lng !== stop.lng || start.lat !== stop.lat) {
                        lineSegments.push({
                            lng_start: start.lng,
                            lat_start: start.lat,
                            lng_stop: stop.lng,
                            lat_stop: stop.lat,
                        });
                    }
                }

                // 标记当前线段为已完成
                if (this.currentPolyline) {
                    this.currentPolyline.isCompleted = true;
                    // 从临时数组移动到已完成数组
                    const index = this.overlays.tempPolylines.indexOf(this.currentPolyline);
                    if (index > -1) {
                        this.overlays.tempPolylines.splice(index, 1);
                        this.overlays.polylines.push(this.currentPolyline);
                    }
                }

                this.currentLine = [];
                this.lastPoint = null;
                this.currentPolyline = null;

                this.stopDrawing({ line: lineSegments });
            } else {
                ElMessage.warning('请至少绘制两点以完成折线');
            }
        }
    }

    _handleKeyDown(e) {
        if (e.key === 'Escape') {
            if (this.mode !== 'none') {
                // 清理临时预览线
                if (this.tempLine) {
                    this.map.removeOverlay(this.tempLine);
                    this.tempLine = null;
                }

                // 清理未完成的当前线段
                if (this.currentPolyline && !this.currentPolyline.isCompleted) {
                    this.map.removeOverlay(this.currentPolyline);
                    const index = this.overlays.tempPolylines.indexOf(this.currentPolyline);
                    if (index > -1) {
                        this.overlays.tempPolylines.splice(index, 1);
                    }
                }

                // 重置当前绘制状态
                this.currentPolyline = null;
                this.currentLine = [];
                this.lastPoint = null;

                // 调用取消回调
                if (this.options.onDrawCancel) {
                    this.options.onDrawCancel();
                }

                this.stopDrawing(null);
            }
        }
        else if (e.ctrlKey && e.key === 'z') {
            this.undo();
        }
    }

    _snapToNearestPoint(point) {
        let closestPoint = null;
        let minDistance = Infinity;

        // 检查所有已存在的点
        this.overlays.markers.forEach(marker => {
            const markerPoint = marker.getPosition();
            const distance = this._calculateDistance(point, markerPoint);
            if (distance < minDistance && distance < this.snapDistance) {
                minDistance = distance;
                closestPoint = markerPoint;
            }
        });

        // 检查所有已存在的线
        this.overlays.polylines.forEach(polyline => {
            const path = polyline.getPath();
            path.forEach(pathPoint => {
                const distance = this._calculateDistance(point, pathPoint);
                if (distance < minDistance && distance < this.snapDistance) {
                    minDistance = distance;
                    closestPoint = pathPoint;
                }
            });
        });

        return closestPoint ? { lng: closestPoint.lng, lat: closestPoint.lat } : { lng: point.lng, lat: point.lat };
    }

    _calculateDistance(point1, point2) {
        const pixel1 = this.map.pointToPixel(new BMapGL.Point(point1.lng, point1.lat));
        const pixel2 = this.map.pointToPixel(new BMapGL.Point(point2.lng, point2.lat));
        const dx = pixel1.x - pixel2.x;
        const dy = pixel1.y - pixel2.y;
        return Math.sqrt(dx * dx + dy * dy);
    }

    undo() {
        if (this.undoStack.length > 0) {
            const lastAction = this.undoStack.pop();
            if (lastAction.type === 'point') {
                this.map.removeOverlay(lastAction.overlay);
                const index = this.overlays.markers.indexOf(lastAction.overlay);
                if (index > -1) {
                    this.overlays.markers.splice(index, 1);
                }
            } else if (lastAction.type === 'line') {
                this.map.removeOverlay(lastAction.overlay);
                // 从已完成的线段数组中移除
                const index = this.overlays.polylines.indexOf(lastAction.overlay);
                if (index > -1) {
                    this.overlays.polylines.splice(index, 1);
                }
            } else if (lastAction.type === 'linePoint') {
                const path = lastAction.polyline.getPath();
                path.pop(); // 移除最后一个点

                if (path.length < 2) {
                    // 如果线段只剩下一个点，则删除整条线
                    this.map.removeOverlay(lastAction.polyline);
                    // 根据线段状态从相应数组中移除
                    if (lastAction.polyline.isCompleted) {
                        const index = this.overlays.polylines.indexOf(lastAction.polyline);
                        if (index > -1) {
                            this.overlays.polylines.splice(index, 1);
                        }
                    } else {
                        const index = this.overlays.tempPolylines.indexOf(lastAction.polyline);
                        if (index > -1) {
                            this.overlays.tempPolylines.splice(index, 1);
                        }
                    }
                    this.currentPolyline = null;
                    this.currentLine = [];
                    this.lastPoint = null;
                } else {
                    lastAction.polyline.setPath(path);
                    this.currentLine = path.map(p => ({ lng: p.lng, lat: p.lat }));
                    this.lastPoint = this.currentLine[this.currentLine.length - 1];
                }
            }
        }
    }
}